package com.zisu.spingcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @Author: 蔡翔
 * @Date: 2020/9/5 14:04
 * @Version 1.0
 */
@Service
public class PaymentService {
    //服务降级

    //成功
    public String paymentInfo_OK(Integer id){
        return "线程池："+Thread.currentThread().getName()+"   paymentInfo_OK,id：  "+id+"\t"+"哈哈哈"  ;
    }

    //失败
    //@HystrixCommand 注解的意思就是 当paymentInfo_TimeOut 这个方法执行不下去的时候（包括超时和程序异常） 就调用paymentInfo_TimeOutHandler 来兜底，，参数要保持一致
    //并且 当超出了 以下注解配置 的3s 时间 那么当前执行这个业务的超时线程会被 中断，然后去执行兜底方法
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")  //3秒钟以内走正常的业务逻辑，超过3秒（超时错误）给个兜底方法
    })
    public String paymentInfo_TimeOut(Integer id){
        //int age = 10/0;
        int timeNumber = id;

        try { TimeUnit.SECONDS.sleep(timeNumber); }catch (Exception e) {e.printStackTrace();}
        return "线程池："+Thread.currentThread().getName()+"   paymentInfo_TimeOut,id：  "+id+"\t"+"呜呜呜"+" 耗时(秒)"+timeNumber;
    }

    public String paymentInfo_TimeOutHandler(Integer id){
        return "线程池："+Thread.currentThread().getName()+"   paymentInfo_TimeOutHandler,id：  "+id+"\t"+"系统繁忙 或系统报错 请稍后再试";
    }


    //服务熔断
    //服务熔断的作用就是 失败了大量次数以后 就算你再输入正确的 数 也是不能成功的，过一段时间后就会恢复
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),  //是否开启断路器
            //下面注解 都是and 类型，就是：请求次数达到10次并且 失败率达到60% 后就跳槽
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),   //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),  //时间范围
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), //失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        if (id < 0){
            throw new RuntimeException("*****id 不能负数");
        }
        //IdUtil.simpleUUID(); 就是获取唯一id
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"\t"+"调用成功,流水号："+serialNumber;
    }
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "id 不能负数，请稍候再试,(┬＿┬)/~~     id: " +id;
    }

}
